#pragma GCC optimize(2)
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <vector>

using namespace std;
using LL = long long;
const int N = 1010;
const int inf = 1e9 + 10;

int n, m;
int A[N][N];
int f[N][2][2];


bool check(int row, int cur, int up, int down){
    if(row == 1){
        for(int i = 1; i <= m; i ++){
            int t = 0;
            if((A[row][i] ^ cur) == (A[row + 1][i] ^ down)) t = 1;
            if(i > 1 && A[row][i] == A[row][i - 1]) t = 1;
            if(i < m && A[row][i] == A[row][i + 1]) t = 1;

            if(!t) return false;
        }

    }else{
        for(int i = 1; i <= m; i ++){
            int t = 0;
            if(((A[row][i] ^ cur) == (A[row + 1][i] ^ down)) || ((A[row][i] ^ cur) == (A[row - 1][i] ^ up))) t = 1;
            if(i > 1 && A[row][i] == A[row][i - 1]) t = 1;
            if(i < m && A[row][i] == A[row][i + 1]) t = 1;

            if(!t) return false;
        }
    }

    if(row == n - 1){
        row ++;
        for(int i = 1; i <= m; i ++){
            int t = 0;
            if((A[row][i] ^ down) == (A[row - 1][i] ^ cur)) t = 1;
            if(i > 1 && A[row][i] == A[row][i - 1]) t = 1;
            if(i < m && A[row][i] == A[row][i + 1]) t = 1;

            if(!t) return false;
        }
    }

    return true;

}



void solve(){
    cin >> n >> m;
    for(int i = 1; i <= n; i ++){
        for(int j = 1; j <= m; j ++){
            cin >> A[i][j];
        }
    }

    for(int i = 0; i <= n; i ++){
        f[i][0][0] = f[i][0][1] = f[i][1][0] = f[i][1][1] = inf;
    }

    f[1][0][0] = 0;
    f[1][1][0] = 0;
    f[1][0][1] = 1;
    f[1][1][1] = 1;

    for(int i = 2; i <= n; i ++){
        for(int j = 0; j <= 1; j ++){
            for(int k = 0; k <= 1; k ++){
                for(int u = 0; u <= 1; u ++){
                    if(check(i - 1, j, u, k)){
                        f[i][j][k] = min(f[i][j][k], f[i - 1][u][j] + k);
                    }
                }
            }
        }
    }


    int res = inf;

    res = min(res, min(f[n][0][0], min(f[n][0][1], min(f[n][1][0], f[n][1][1]))));
    if(res >= inf){
        cout << -1 << '\n';
        return;
    }else{
        cout << res << '\n';
        return;
    }
}

int main(){
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    solve();
    return 0;
}